package cz.library.database;

import cz.library.entityDAO.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {
    // private static int TIMEOUT = 240;

    private final String OracleDriver = "oracle.jdbc.driver.OracleDriver";
    private final String DatabaseUrl = "jdbc:oracle:thin:@dbedu.cs.vsb.cz:1521:oracle";
    private final String User = "lat054";
    private final String Pass = "lattisek";
    private Connection mConnection;
    public AutorDAO autorDAO;
    public KnihaDAO knihaDAO;
    public NakladatelstviDAO nakladatelstviDAO;
    public NavstevnikDAO navstevnikDAO;
    public PujcenoDAO pujcenoDAO;

    public Connection Connection() {
        return mConnection;
    }

    public Database() {
        mConnection = GetConnection();
        autorDAO = new AutorDAO(this);
        knihaDAO = new KnihaDAO(this);
        nakladatelstviDAO = new NakladatelstviDAO(this);
        navstevnikDAO = new NavstevnikDAO(this);
        pujcenoDAO = new PujcenoDAO(this);
    }

    private Connection GetConnection() {
        Connection conn;
        try {
            Class.forName(OracleDriver).newInstance();
            conn = DriverManager.getConnection(DatabaseUrl, User, Pass);
            conn.setAutoCommit(true);
        } catch (Exception ex) {
            System.err.println("Nebylo možné navázat spojení\nChyba " + ex.getMessage());
            conn = null;
        }
        return conn;
    }

    /**
     * Close.
     **/
    public boolean Close() {
        boolean ret = true;
        try {
            mConnection.close();
        } catch (SQLException ex) {
            ret = false;
        }
        return ret;
    }

    /**
     * Begin a transaction.
     **/
    public boolean BeginTransaction() {
        boolean ret = true;
        try {
            mConnection.setAutoCommit(false);
            mConnection.setTransactionIsolation(Connection.TRANSACTION_NONE);
        } catch (SQLException ex) {
            ret = false;
        }
        return ret;
    }

    /**
     * End a transaction.
     **/
    public boolean EndTransaction() {
        boolean ret = true;
        try {
            mConnection.commit();
            mConnection.setAutoCommit(true);
        } catch (SQLException ex) {
            ret = false;
        }
        return ret;
    }

    /**
     * If a transaction is failed call it.
     **/
    public boolean Rollback() {
        boolean ret = true;
        try {
            mConnection.rollback();
            mConnection.setAutoCommit(true);
        } catch (SQLException ex) {
            ret = false;
        }
        return ret;
    }
}
